package ltd.jdsoft.cute.channel.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ltd.jdsoft.cute.cache.CacheClient;
import ltd.jdsoft.cute.cache.CacheKeyUtil;
import ltd.jdsoft.cute.cache.callback.GetCallback;
import ltd.jdsoft.cute.channel.dao.OrgIPConfigDAO;
import ltd.jdsoft.cute.channel.model.OrgIPConfig;

/**
 * 机构IP白名单操作的service层
 * 
 * @author zhengzhq
 *
 */
@Service
public class OrgIPConfigService {

  @Autowired
  private OrgIPConfigDAO orgIPConfigDAO;
  private CacheKeyUtil keyUtil = new CacheKeyUtil(OrgIPConfig.class);

  public void add(OrgIPConfig orgIpConfig) {
    orgIPConfigDAO.add(orgIpConfig);
    CacheClient.remove(keyUtil.getGroupKey(".org." + orgIpConfig.getOrgId()));
  }

  public void update(OrgIPConfig orgIpConfig) {
    orgIPConfigDAO.update(orgIpConfig);
    // 删除该机构对应的所有IP缓存，为方便处理让该机构所有的IP白名单缓存失效，记录不多，所以性能上基本一样
    CacheClient.remove(keyUtil.getGroupKey(".org." + orgIpConfig.getOrgId()));
  }

  public void delete(long id) {
    OrgIPConfig orgServerIP = orgIPConfigDAO.getById(id);
    orgIPConfigDAO.delete(id);
    // 删除该机构对应的所有IP缓存，为方便处理让该机构所有的IP白名单缓存失效，记录不多，所以性能上基本一样
    CacheClient.remove(keyUtil.getGroupKey(".org." + orgServerIP.getOrgId()));
  }

  public OrgIPConfig get(long orgId, String ip) {
    return CacheClient.get(keyUtil.getRecKey(".orgId." + orgId + ".ip." + ip),
        new GetCallback<OrgIPConfig>() {

          @Override
          public String getCacheGroup() {
            // 结果放到组里面
            return keyUtil.getGroupKey(".org." + orgId);
          }

          @Override
          public OrgIPConfig getObject() {
            return orgIPConfigDAO.get(orgId, ip);
          }
        });
  }

  public OrgIPConfig getById(long id, long orgId) {
    return CacheClient.get(keyUtil.getRecKey("." + id), new GetCallback<OrgIPConfig>() {

      @Override
      public String getCacheGroup() {
        return keyUtil.getGroupKey(".org." + orgId);
      }

      @Override
      public OrgIPConfig getObject() {
        return orgIPConfigDAO.getById(id);
      }
    });
  }

  public List<OrgIPConfig> getByOrgId(long orgId) {
    return CacheClient.get(keyUtil.getRecKey(".orgId." + orgId),
        new GetCallback<List<OrgIPConfig>>() {

          @Override
          public String getCacheGroup() {
            return keyUtil.getGroupKey(".org." + orgId);
          }

          @Override
          public List<OrgIPConfig> getObject() {
            return orgIPConfigDAO.getByOrgId(orgId);
          }
        });
  }
}
